from django.shortcuts import render

# Create your views here.

import json
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from . import models

def hello(request):
    resp = {
        'code': 0,
        'msg': 'SUCCESS',
        'data': 'Hello, World',
    }
    return HttpResponse(json.dumps(resp), content_type="application/json")

def notFound(request):
    resp = {
        'code': -1,
        'msg': '404 NOT FOUND',
    }
    return HttpResponse(json.dumps(resp), content_type="application/json")

def getNews(request):
    page = request.GET['page']
    size = request.GET['size']
    l = models.NewsAgg.objects.all().order_by('-id')
    return __pager(l, page, size)

def __pager(l, page, size):
    paginator = Paginator(l, size)
    try:
        data = paginator.page(page)
    except EmptyPage:
        return JsonResponse({
            'code': 0,
            'msg': 'SUCCESS',
            'data': {
                'total': paginator.count,
                'list': [],
            }
        })
    except:
        return JsonResponse({
            'code': -1,
            'msg': 'FAIL',
            'data': 'ERROR page/size',
        })
    resp = {
        'code': 0,
        'msg': 'SUCCESS',
        'data': {
            'total': paginator.count,
            'list': json.loads(serializers.serialize("json", data)),
        },
    }
    return JsonResponse(resp)

def search(request):
    page = request.GET['page']
    size = request.GET['size']
    text = request.GET['text']
    l = models.NewsAgg.objects.filter(title__contains=text).order_by('-id')
    return __pager(l, page, size)
